#  ______     ______     ______     ______     ______   __     ______     ______
# /\  ___\   /\  == \   /\  ___\   /\  __ \   /\__  _\ /\ \   /\___  \   /\  ___\
# \ \ \____  \ \  __<   \ \  __\   \ \  __ \  \/_/\ \/ \ \ \  \/_/  /__  \ \  __\
#  \ \_____\  \ \_\ \_\  \ \_____\  \ \_\ \_\    \ \_\  \ \_\   /\_____\  \ \_____\
#   \/_____/   \/_/ /_/   \/_____/   \/_/\/_/     \/_/   \/_/   \/_____/   \/_____/

# Code is licensed under CC-BY-NC-ND 4.0 unless otherwise specified.
# https://creativecommons.org/licenses/by-nc-nd/4.0/
# You CANNOT edit this file without direct permission from the author.
# You can redistribute this file without any changes.

# meta developer: @creaz_mods
# scope: hikka_min 1.6.2
# requires: gpt4free

from asyncio import sleep

from gpt4free import you
from hikkatl.types import Message
from mistune import html

from .. import loader, utils  # type: ignore


@loader.tds
class GPT4Free(loader.Module):
    """Module for interacting with GPT without API-key. Unstable"""

    strings = {
        "name": "GPT4Free",
        "wait": (
            "<emoji document_id=5443038326535759644>💬</emoji><b> GPT is generating"
            " response, please wait</b>"
        ),
        "quest": (
            "{answer}\n\n\n<emoji document_id=5452069934089641166>❓</emoji><b> Your"
            " question to ChatGPT was:</b> <code>{args}</code>"
        ),
        "args_err": (
            "<emoji document_id=5210952531676504517>❌</emoji><b> You didn't ask a"
            " question GPT</b>"
        ),
        "api_err": (
            "<emoji document_id=5210952531676504517>❌</emoji><b> Error on you.com"
            " servers. Try repeating your question</b>"
        ),
        "floodwait": (
            "<emoji document_id=6332573220868196043>🕓</emoji><b> You have reached the"
            " request per minute limit. Retry your request in 10-40 seconds</b>"
        ),
        "cleared": (
            "<emoji document_id=5206607081334906820>✔️</emoji><b> Dialog cleared"
            " successfully</b>"
        ),
    }

    strings_ru = {
        "wait": (
            "<emoji document_id=5443038326535759644>💬</emoji><b> GPT генерирует ответ,"
            " подождите</b>"
        ),
        "quest": (
            "{answer}\n\n\n<emoji document_id=5452069934089641166>❓</emoji><b> Ваш"
            " вопрос к ChatGPT был:</b> <code>{args}</code>"
        ),
        "args_err": (
            "<emoji document_id=5210952531676504517>❌</emoji><b> Вы не задали вопрос"
            " GPT</b>"
        ),
        "api_err": (
            "<emoji document_id=5210952531676504517>❌</emoji><b> Ошибка на серверах"
            " you.com. Попробуйте повторить свой вопрос</b>"
        ),
        "floodwait": (
            "<emoji document_id=6332573220868196043>🕓</emoji> Вы достигли лимита"
            " запросов в минуту. Повторите свой запрос через 10-40 секунд"
        ),
        "cleared": (
            "<emoji document_id=5206607081334906820>✔️</emoji><b> Диалог успешно"
            " очищен</b>"
        ),
    }

    strings_de = {
        "wait": (
            "<emoji document_id=5443038326535759644>💬</emoji><b> GPT generiert eine"
            " Antwort. Bitte warten...</b>"
        ),
        "quest": (
            "{answer}\n\n\n<emoji document_id=5452069934089641166>❓</emoji><b> Ihre"
            " Frage an ChatGPT lautet:</b> <code>{args}</code>"
        ),
        "args_err": (
            "<emoji document_id=5210952531676504517>❌</emoji><b> Sie haben keine Frage"
            " an GPT gestellt.</b>"
        ),
        "api_err": (
            "<emoji document_id=5210952531676504517>❌</emoji><b> Es gab einen Fehler"
            " auf den you.com- Servern. Bitte stellen Sie Ihre Frage erneut.</b>"
        ),
        "floodwait": (
            "<emoji document_id=6332573220868196043>🕓</emoji> Sie haben das Limit von"
            " Anfragen pro Minute erreicht. Bitte wiederholen Sie Ihre Anfrage in 10-40"
            " Sekunden."
        ),
        "cleared": (
            "<emoji document_id=5206607081334906820>✔️</emoji><b> Der Dialog wurde"
            " erfolgreich gelöscht.</b>"
        ),
    }

    strings_ru = {
        "wait": (
            "<emoji document_id = 5443038326535759644> 💬 </emoji><B > GPT genera una"
            " respuesta, espera</B>"
        ),
        "quest": (
            "{answer}\n\n\n<emoji document_id = 5452069934089641166> ❓ </emoji><B > su"
            " la pregunta para ChatGPT fue:< / B><code > {args}</code>"
        ),
        "args_err": (
            "<emoji document_id = 5210952531676504517 > ❌ < / emoji > <B > no has"
            " hecho la pregunta GPT</b>"
        ),
        "api_err": (
            "<emoji document_id = 5210952531676504517> ❌ </emoji><B > Error en los"
            " servidores you.com. Intenta repetir tu pregunta< / b>"
        ),
        "floodwait": (
            "<emoji document_id = 6332573220868196043 > 🕓 < / emoji> has alcanzado el"
            " límite consultas por minuto. Repita su solicitud en 10-40 segundos"
        ),
        "cleared": (
            "<emoji document_id=5206607081334906820> ✔️ </emoji> < B> diálogo con éxito"
            "despejado</b>"
        ),
    }

    @loader.command(
        ru_doc="- ваш вопрос к ChatGPT",
        es_doc="- tu pregunta a ChatGPT",
        de_doc="- deine Frage an ChatGPT",
    )
    async def gpt(self, m: Message):
        """- question to ChatGPT"""
        args = utils.get_args_raw(m)
        try:
            if not args:
                args = (await m.get_reply_message()).message  # type: ignore
        except:
            return await utils.answer(m, self.strings["args_err"])

        if not self._db.get(self.name, "chat"):
            chat = []
        else:
            chat = self._db.get(self.name, "chat")

        m = await utils.answer(m, self.strings["wait"])

        response = you.Completion.create(
            prompt=args, chat=self._db.get(self.name, "chat"), include_links=False
        )
        while response.text == "Unable to fetch the response, Please try again.":
            await sleep(1)
            response = you.Completion.create(
                prompt=args, chat=self._db.get(self.name, "chat")
            )

        chat.append({"question": args, "answer": response.text})
        self._db.set(self.name, "chat", chat)

        answer = bytes(response.text, "utf-8").decode("unicode_escape")  # type: ignore
        await utils.answer(
            m,
            self.strings["quest"].format(answer=html(answer), args=args),
        )

    @loader.command(
        ru_doc="- очистить диалог", es_doc="- diálogo claro", de_doc="- klaren Dialog"
    )
    async def resg(self, m: Message):
        """- clear dialog"""
        self._db.set(self.name, "chat", None)
        await utils.answer(m, self.strings["cleared"])
